package com.itboye.sunsun.luntan;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsun.adapter.LunTanDetailAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LunTanHomePageBean;
import com.itboye.sunsun.beans.LuntanForumBean;
import com.itboye.sunsun.beans.LuntanForumBean.LuntanForumItemBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.Spanned2String;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.umeng.socialize.utils.Log;

public class LunTanPinDaoActivity extends BaseActivity implements
		OnItemClickListener {
	private MyGridView mOtherGv;
	private DragGridView mUserGv;
	private List<String> mUserList = new ArrayList<String>();
	private List<String> mOtherList = new ArrayList<String>();
	private OtherAdapter mOtherAdapter;
	private DragAdapter mUserAdapter;
	protected ArrayList<LuntanForumItemBean> arrayListForm;
	String fid;
	public static String ffid;
	private ImageView imgTop;
	ArrayList<LuntanForumItemBean> arrayLisForumItemBeans;
	private boolean hasChannel;

	private ImageView back;
private Button btnOk;
	List<LuntanForumItemBean> arrayLis = new ArrayList<LuntanForumItemBean>();
	StringBuffer fids = new StringBuffer();
	private ArrayList<LuntanForumItemBean> arrayListUnfocus, arrayListFocus;
	OnClickListener deleteOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (arrayListFocus.size() <= 1) {
				ByAlert.alert("至少需要一个 主题论坛 ");
				return;
			}
			int position = (int) v.getTag();
			LuntanForumItemBean channel = arrayListFocus.get(position);// 获取点击的频道内容
			arrayListFocus.get(position).setDeleteStatus("0");
			// Iterator<LuntanForumItemBean> iterator=arrayListFocus.iterator();
			for (int i = 0; i < arrayListFocus.size(); i++) {
				if (position == i) {
					arrayListFocus.remove(i);
					break;
				}
			}
	
			// 添加到最后一个
			if (mOtherAdapter == null){
				mOtherAdapter = new OtherAdapter(App.ctx, arrayListUnfocus,
						false);
				mOtherGv.setAdapter(mOtherAdapter);
			}
			mOtherAdapter.addItem(channel);
	
			mUserAdapter.notifyDataSetChanged();
			mOtherAdapter.notifyDataSetChanged();
		}
	};

	protected void onCreate(Bundle arg0) {

		super.onCreate(arg0);

		setContentView(R.layout.activity_pindao);
		setStatusBarColor(R.color.home_blue);

		arrayListUnfocus = new ArrayList<LuntanForumBean.LuntanForumItemBean>();
		arrayListFocus = new ArrayList<LuntanForumBean.LuntanForumItemBean>();
		showProgressDialog("正在获取论坛信息", true);
		initView();
		getFocusForum();
		getUnFocusForum();
		
		
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LoginController.onPinDaoCommentclik(LunTanPinDaoActivity.this, null);
			}
		});
		imgTop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(0, 0);
			}
		});

		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	public void getUnFocusForum() {
		MyJsonRequest.Builder<LuntanForumBean> builder = new MyJsonRequest.Builder<LuntanForumBean>()
				.param("uid",
						(String) SPUtils.get(App.ctx, null, SPContants.USER_ID,
								"")).typeKey("BY_BbsFavorite_nolikequery")
				.apiVer("100")
				.requestListener(new XRequestListener<LuntanForumBean>() {

					@Override
					public void onResponse(LuntanForumBean orderBean) {//
						if (orderBean.getList() != null) {
							arrayListUnfocus.clear();
							arrayListUnfocus.addAll(orderBean.getList());
							mOtherAdapter = new OtherAdapter(App.ctx,
									arrayListUnfocus, false);
							mOtherGv.setAdapter(mOtherAdapter);
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// Toast.makeText(LunTanDetailActivity.this, "msg" +
						// msg,
						// 0).show();
					}
				});
		MyJsonRequest<LuntanForumBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void getFocusForum() {
		// TODO Auto-generated method stub
		MyJsonRequest.Builder<LuntanForumBean> builder = new MyJsonRequest.Builder<LuntanForumBean>()
				.param("uid",
						(String) SPUtils.get(App.ctx, null, SPContants.USER_ID,
								"")).typeKey("BY_BbsFavorite_query")
				.apiVer("100")
				.requestListener(new XRequestListener<LuntanForumBean>() {

					@Override
					public void onResponse(LuntanForumBean orderBean) {//
						if (orderBean.getList() != null) {
							arrayListFocus.clear();
							arrayListFocus.addAll(orderBean.getList());
							mUserAdapter = new DragAdapter(App.ctx,
									arrayListFocus, true, deleteOnClickListener);
							mUserGv.setAdapter(mUserAdapter);
						}
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
		MyJsonRequest<LuntanForumBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// changeChannels();
//			showDialog();
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void changeChannels() {
		
		
		showProgressDialog("数据提交中", true);
		fids = new StringBuffer();
		for (int i = 0; i < arrayListFocus.size(); i++) {
			Log.v("title", arrayListFocus.get(i).getName() + ","
					+ arrayListFocus.get(i).getFid());
			fids.append(arrayListFocus.get(i).getFid() + ",");
		}
		Log.v("title", fids + "");
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.typeKey("BY_BbsFavorite_deletesave")
				.param("favorite_id", fids.substring(0, fids.length() - 1))
				.apiVer("100")
				.param("uid",
						SPUtils.get(this, null, SPContants.USER_ID, "") + "")

				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						ByAlert.alert(orderBean + "");
						Intent broad = new Intent(
								LunTanDetailActivity.CLOSELUNTANDETAIL);
						sendBroadcast(broad);
						Intent intent = new Intent(LunTanPinDaoActivity.this,
								LunTanDetailActivity.class);
						intent.putExtra("list", arrayListFocus);
						startActivity(intent);
						finish();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
						// finish
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void initView() {

		// arrayLisForumItemBeans = App.arrayLisForumItemBeans;
		// arrayListForm = App.arrayLisForumItemBeans;
		mUserGv = (DragGridView) findViewById(R.id.userGridView);
		mOtherGv = (MyGridView) findViewById(R.id.otherGridView);

		mUserGv.setOnItemClickListener(this);
		mOtherGv.setOnItemClickListener(this);

	}

	/**
	 * 获取点击的Item的对应View，
	 * 因为点击的Item已经有了自己归属的父容器MyGridView，所有我们要是有一个ImageView来代替Item移动
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	/**
	 * 获取移动的VIEW，放入对应ViewGroup布局容器
	 * 
	 * @param viewGroup
	 * @param view
	 * @param initLocation
	 * @return
	 */
	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int x = initLocation[0];
		int y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		mLayoutParams.leftMargin = x;
		mLayoutParams.topMargin = y;
		view.setLayoutParams(mLayoutParams);
		return view;
	}

	/**
	 * 创建移动的ITEM对应的ViewGroup布局容器 用于存放我们移动的View
	 */
	private ViewGroup getMoveViewGroup() {
		// window中最顶层的view
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);
		return moveLinearLayout;
	}

	/**
	 * 点击ITEM移动动画
	 * 
	 * @param moveView
	 * @param startLocation
	 * @param endLocation
	 * @param moveChannel
	 * @param clickGridView
	 */
	private void MoveAnim(View moveView, int[] startLocation,
			int[] endLocation, final String moveChannel,
			final GridView clickGridView, final boolean isUser) {
		int[] initLocation = new int[2];
		// 获取传递过来的VIEW的坐标
		moveView.getLocationInWindow(initLocation);
		// 得到要移动的VIEW,并放入对应的容器中
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView,
				initLocation);
		// 创建移动动画
		TranslateAnimation moveAnimation = new TranslateAnimation(
				startLocation[0], endLocation[0], startLocation[1],
				endLocation[1]);
		moveAnimation.setDuration(300L);// 动画时间
		// 动画配置
		AnimationSet moveAnimationSet = new AnimationSet(true);
		moveAnimationSet.setFillAfter(false);// 动画效果执行完毕后，View对象不保留在终止的位置
		moveAnimationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(moveAnimationSet);
		moveAnimationSet
				.setAnimationListener(new Animation.AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
					}

					@Override
					public void onAnimationRepeat(Animation animation) {
					}

					@Override
					public void onAnimationEnd(Animation animation) {
						moveViewGroup.removeView(mMoveView);
						// 判断点击的是DragGrid还是OtherGridView
						if (isUser == true) {

							mOtherAdapter.setVisible(true);
							mOtherAdapter.notifyDataSetChanged();
							mUserAdapter.remove();
						} else if (isUser == false) {
							mUserAdapter.setVisible(true);
							mUserAdapter.notifyDataSetChanged();
							mOtherAdapter.remove();
						}
					}
				});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			final int position, long id) {

		switch (parent.getId()) {
		case R.id.userGridView:
			Iterator<LuntanForumItemBean> iterator = arrayListFocus.iterator();
			while (iterator.hasNext()) {
				LuntanForumItemBean bean = iterator.next();

				bean.setDeleteStatus(bean.getDeleteStatus().equals("0") ? "1"
						: "0");
			}
			mUserAdapter.notifyDataSetChanged();
			break;
		case R.id.otherGridView:
			if (arrayListFocus.get(0).getDeleteStatus().equals("1")) {// focus中的频道处于删除状态不允许添加
				ByAlert.alert("频道处于删除状态哦");
				return;
			}
			final ImageView moveImageView2 = getView(view);
			if (moveImageView2 != null) {
				TextView newTextView = (TextView) view
						.findViewById(R.id.text_item);
				final int[] startLocation = new int[2];
				newTextView.getLocationInWindow(startLocation);
				final LuntanForumItemBean channel = ((OtherAdapter) parent
						.getAdapter()).getItem(position);
				for (int j = 0; j < startLocation.length; j++) {
					if (j < arrayListFocus.size()) {
						if (channel.getName().equals(
								arrayListFocus.get(j).getName())) {
							hasChannel = true;
							break;
						}
					} else {
						break;
					}
				}
				if (hasChannel == true) {
					ByAlert.alert("当前频道已存在哦!");
					return;
				}
				mUserAdapter.setVisible(false);
				// 添加到最后一个
				mUserAdapter.addItem(channel);
				new Handler().postDelayed(new Runnable() {
					public void run() {
						try {
							int[] endLocation = new int[2];
							// 获取终点的坐标
							mUserGv.getChildAt(mUserGv.getLastVisiblePosition())
									.getLocationInWindow(endLocation);
							MoveAnim(moveImageView2, startLocation,
									endLocation, channel.getName(), mOtherGv,
									false);
							mOtherAdapter.setRemove(position);
						} catch (Exception localException) {
						}
					}
				}, 50L);
			}
			break;
		default:
			break;
		}

	}

	private void showDialog() {
		// TODO Auto-generated method stub
		final AlertDialog alertDialog = new AlertDialog.Builder(
				LunTanPinDaoActivity.this).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.dialog_save);
		TextView tv_title = (TextView) window.findViewById(R.id.title);
		tv_title.setText("提示");
		TextView tv_message = (TextView) window.findViewById(R.id.message);
		tv_message.setText("是否执行 当前更改?");
		Button btn_save = (Button) window.findViewById(R.id.save);
		btn_save.setText("是");

		Button btn_noSave = (Button) window.findViewById(R.id.noSave);
		btn_noSave.setText("否");
		Button canButton = (Button) window.findViewById(R.id.cancel);
		btn_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				
				String uri = (String) SPUtils.get(App.ctx, null, SPContants.AVATAR_URL,
						"");
				if(uri!=null || uri!=""){
					changeChannels();
				}else
					
				// String save_title = title.getText().toString().trim();
				// String save_content = content.getText().toString().trim();
				// StringBuilder builder = new StringBuilder();
				// for (int i = 0; i < imgPath.size(); i++) {
				// builder.append(imgPath.get(i) + ",");
				// }
				//
				// String s = "";
				// if (builder.length() > 0) {
				// s = builder.toString().substring(0, builder.length() - 1);
				// }
				// dbManager.delete(uid);
				// long result = dbManager.addNote(uid, save_title,
				// Spanned2String.parse(content.getText()), s);
				// if (result <= 0) {
				// Toast.makeText(FaBiaoTieZiActivity.this, "保存草稿失败", 0)
				// .show();
				// } else {
				// Toast.makeText(FaBiaoTieZiActivity.this, "保存草稿成功", 0)
				// .show();
				// }
				finish();
			}
		});
		btn_noSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// dbManager.delete(uid);
				finish();
			}
		});
		canButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.dismiss();
			}
		});

	}

}
